'use strict';

module.exports = app => {
  /**
  * @controller UserController (用户的Controller)
  */
  class UserController extends app.Controller {
    * index() {
      /**
      * @summary 查询用户全部数据
      * @description 查询用户全部数据
      * @router get /api/user/list
      * @request ()
      * @response 200 JsonBodyResponse  返回结果。
      */
      const { ctx } = this;
      const result = yield this.service.user.index();
      ctx.body = result;
    }

    * create() {
      /**
      * @summary 新增用户信息
      * @description 新增用户信息
      * @router post /api/user
      * @request body createUserRequest *body
      * @response 200 createUserResponse  返回结果。
      */
      const { ctx } = this;
      console.log(ctx.request.body)
      const result = yield this.service.user.create(ctx.request.body);
      ctx.body = result;
    }

    * update() {
      /**
      * @summary 修改用户信息
      * @description 修改用户信息
      * @router put /api/user/{id}
      * @request path integer *id 标识
      * @request body updateUserRequest *body
      * @response 200 updateUserResponse  返回结果。
      */
      const { ctx } = this;
      const result = yield this.service.user.update(ctx.params.id, ctx.request.body);
      ctx.body = result;
    }

    * destroy() {
      /**
      * @summary 修改用户信息
      * @description 修改用户信息
      * @router delete /api/user/{id}
      * @request path integer *id 标识
      * @response 200 updateUserResponse  返回结果。
      */
      const { ctx } = this;
      const result = yield this.service.user.destroy(ctx.params.id);
      ctx.body = result;
    }

    * upload() {
      const fs = require('fs');
      const dayjs = require('dayjs');
      const path = require('path');
      // 故名思意 异步二进制 写入流
      const awaitWriteStream = require('await-stream-ready').write;
      // 管道读入一个虫洞。
      const sendToWormhole = require('stream-wormhole');
      /**
      * @summary 上传文件
      * @description 上传文件
      * @router post /api/user/file
      * @request formData file *file 文件
      * @response 200 uploadResponse  返回结果。
      */
      // const { request } = ApiParams;
      const { ctx } = this;
      const stream = yield ctx.getFileStream();
      const uplaodBasePath = 'app/public/uploads';
      const filename = `${Date.now()}${Number.parseInt(
        Math.random() * 1000
      )}${path.extname(stream.filename).toLocaleLowerCase()}`;
      const dirname = dayjs(Date.now()).format('YYYY/MM/DD');
      function mkdirsSync(dirname) {
        console.log(dirname);
        if (fs.existsSync(dirname)) {
          return true;
        } else {
          if (mkdirsSync(path.dirname(dirname))) {
            console.log(dirname);
            fs.mkdirSync(dirname);
            return true;
          }
        }
      }
      mkdirsSync(path.join(uplaodBasePath, dirname));
      // 生成写入路径
      const target = path.join(uplaodBasePath, dirname, filename);
      // 写入流
      const writeStream = fs.createWriteStream(target);
      try {
        // 异步把文件流 写入
        yield awaitWriteStream(stream.pipe(writeStream));
        ctx.body = { url: path.join('/public/uploads', dirname, filename) };
      } catch (err) {
        console.log(err);
        // 如果出现错误，关闭管道
        yield sendToWormhole(stream);
        this.error();
      }
      // this.success({ url: path.join('/public/uploads', dirname, filename) });
      // const result = yield this.service.user.destroy(params.id);
      // this.body = result;
    }
    * upload_file() {
      const fs = require('fs');
      const dayjs = require('dayjs');
      const path = require('path');
      // 故名思意 异步二进制 写入流
      const awaitWriteStream = require('await-stream-ready').write;
      // 管道读入一个虫洞。
      const sendToWormhole = require('stream-wormhole');
      /**
      * @summary 上传文件
      * @description 上传文件
      * @router post /upload_file
      * @request formData file *file 文件
      * @response 200 uploadResponse  返回结果。
      */
      // const { request } = ApiParams;
      const { ctx } = this;
      const stream = yield ctx.getFileStream();
      const uplaodBasePath = 'app/public/uploads';
      const filename = `${Date.now()}${Number.parseInt(
        Math.random() * 1000
      )}${path.extname(stream.filename).toLocaleLowerCase()}`;
      const dirname = dayjs(Date.now()).format('YYYY/MM/DD');
      function mkdirsSync(dirname) {
        console.log(dirname);
        if (fs.existsSync(dirname)) {
          return true;
        } else {
          if (mkdirsSync(path.dirname(dirname))) {
            console.log(dirname);
            fs.mkdirSync(dirname);
            return true;
          }
        }
      }
      mkdirsSync(path.join(uplaodBasePath, dirname));
      // 生成写入路径
      const target = path.join(uplaodBasePath, dirname, filename);
      // 写入流
      const writeStream = fs.createWriteStream(target);
      try {
        // 异步把文件流 写入
        yield awaitWriteStream(stream.pipe(writeStream));
        ctx.body = { url: path.join('/public/uploads', dirname, filename) };
      } catch (err) {
        console.log(err);
        // 如果出现错误，关闭管道
        yield sendToWormhole(stream);
        this.error();
      }
      // this.success({ url: path.join('/public/uploads', dirname, filename) });
      // const result = yield this.service.user.destroy(params.id);
      // this.body = result;
    }
  }
  return UserController;
};

